package com.mmd.intercepter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DefaultInterceptor implements HandlerInterceptor {
    private static final Logger SLOW_URL_LOGGER = LoggerFactory.getLogger("SLOW_URL");
    private static final ThreadLocal<Long> startTime = new ThreadLocal();

    public DefaultInterceptor() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");
        long start = System.currentTimeMillis();
        startTime.set(start);
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long cost = System.currentTimeMillis() - (Long)startTime.get();
        if (cost > 500L) {
            StringBuffer requestURL = request.getRequestURL();
            if (request.getQueryString() != null) {
                requestURL.append("?").append(request.getQueryString());
            }

            String completeURL = requestURL.toString();
            if (cost < 3000L) {
                SLOW_URL_LOGGER.warn("url:{},cost:{}ms", completeURL, cost);
            } else {
                SLOW_URL_LOGGER.error("url:{},cost:{}ms", completeURL, cost);
            }
        }

    }
}
